<template>
  <div class="center" style="margin: 10px 80px">
    <el-row :gutter="20">
      <el-col :span="1"></el-col>
      <el-col :span="21">
        <el-card>
          <el-tabs tab-position="left" style="height: 80%" v-model="activeTopTab">
            <!--我的订单-->
            <el-tab-pane name="myOrder" style="height: 700px">
              <template #label>
                <span><i class="el-icon-s-order"></i> 我的订单</span>
              </template>
              <div class="my-orders">
                <el-card header="我的订单">
                  <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
                    <el-form-item label="订单号" prop="id">
                      <el-input v-model="queryParams.id" placeholder="订单号" clearable style="width: 240px;" size="mini"
                                @keyup.enter.native="handleQuery"/>
                    </el-form-item>
                    <el-form-item label="订单状态" prop="status">
                      <el-select v-model="queryParams.status" placeholder="订单状态" clearable size="mini"
                                 style="width: 240px">
                        <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label"
                                   :value="+dict.value"/>
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                  <el-table :data="orderList" v-if="total>0" :height="tableHeight">
                    <el-table-column label="订单号" width="160" align="center" prop="id"/>
                    <el-table-column label="实际金额" width="100" align="center" prop="totalAmount">
                      <template #default="{row}">
                        <span style="font-weight: bolder">￥{{ Number(row.totalAmount).toFixed(2) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="应付金额" width="100" align="center" prop="payAmount">
                      <template #default="{row}">
                        <span style="color: red;font-weight: bolder">￥{{ Number(row.payAmount).toFixed(2) }}</span>
                      </template>
                    </el-table-column>
                    <!--订单状态(0:待付款 1: 待确认 2:待评价 3:已完成 4:无效订单 5 已关闭-->
                    <el-table-column label="订单状态" align="center" prop="status">
                      <template #default="{row}">
                        <el-tag effect="dark" v-if="row.status ===0">待付款</el-tag>
                        <el-tag effect="dark" v-else-if="row.status===1" type="warning">待确认</el-tag>
                        <el-tag effect="dark" v-else-if="row.status===2" type="info">待评价</el-tag>
                        <el-tag effect="dark" v-else-if="row.status===3" type="success">已完成</el-tag>
                        <el-tag effect="dark" v-else-if="row.status===4" type="danger">无效订单</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="可以获得积分" width="200" align="center" prop="integration"/>
                    <el-table-column label="服务店面地区" width="200" align="center">
                      <template #default="{row}">
                        <span>{{ row.province + row.city + row.county }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="服务店面" width="200" align="center" prop="serviceStoreName"/>
                    <el-table-column label="操作" width="170px">
                      <template #default="{row}">
                        <el-dropdown>
                          <span class="el-dropdown-link">操作<i class="el-icon-arrow-down el-icon--right"></i></span>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item @click.native="toMyOrderItems(row.id)">
                                <el-button size="mini" type="text" icon="el-icon-info">订单详情</el-button>
                              </el-dropdown-item>
                              <el-dropdown-item v-if="row.status===2||row.status===3"
                                                @click.native="toEvaluation(row.id)">
                                <el-button size="mini" type="text" icon="el-icon-edit">
                                  <span v-if="row.status===2">去评价</span>
                                  <span v-else>继续评价</span>
                                </el-button>
                              </el-dropdown-item>
                              <el-dropdown-item @click.native="toProgress(row.id)">
                                <el-button size="mini" type="text" icon="el-icon-question">订单进度</el-button>
                              </el-dropdown-item>
                              <el-dropdown-item @click.native="toConfirm(row.id)" v-if="row.status===1">
                                <el-button size="mini" type="text" icon="el-icon-check">确认已服务</el-button>
                              </el-dropdown-item>
                              <el-dropdown-item @click.native="toPay(row)" v-if="row.status===0">
                                <el-button size="mini" type="text" icon="el-icon-money">立即付款</el-button>
                              </el-dropdown-item>
                              <el-dropdown-item @click.native="cancelOrder(row.id)" v-if="row.status===0">
                                <el-button size="mini" type="text" icon="el-icon-delete">取消订单
                                </el-button>
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!--分页插件-->
                  <el-pagination style="padding: 32px 16px;background: #fff;float: right"
                                 v-if="total>0"
                                 background
                                 layout="total, sizes, prev, pager, next, jumper"
                                 :current-page.sync="queryParams.current"
                                 :page-size.sync="queryParams.size"
                                 :total="total" @current-change="currentChange" @size-change="sizeChange"/>
                  <el-empty v-else description="您还没有呢~">
                  </el-empty>

                </el-card>
              </div>
            </el-tab-pane>
            <!--账户资料-->
            <el-tab-pane name="myAccount" style="height: 700px">
              <template #label>
                <span><i class="el-icon-info"></i> 账户资料</span>
              </template>
              <el-row :gutter="20">
                <el-col :span="7">
                  <el-card header="个人信息">
                    <self-info :user-info="userInfo"></self-info>
                  </el-card>
                </el-col>
                <el-col :span="16">
                  <el-card header="基本资料">
                    <el-tabs v-model="activeSecondTab">
                      <el-tab-pane label="基本资料" name="basicInfo">
                        <basic-info :user-info="userInfo"/>
                      </el-tab-pane>
                      <el-tab-pane label="修改密码" name="resetPwd">
                        <reset-pwd/>
                      </el-tab-pane>
                      <el-tab-pane label="完善信息" name="perfectInfo">
                        <perfect-info :user-info="userInfo"/>
                      </el-tab-pane>
                    </el-tabs>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <!--订单统计-->
            <el-tab-pane name="myOrderStatistical" style="height: 700px">
              <template #label>
                <span><i class="el-icon-s-ticket"></i> 订单统计</span>
              </template>
              <order-statistical/>
            </el-tab-pane>
            <!--支出统计-->
            <el-tab-pane name="topUpStatistical" style="height: 700px">
              <template #label>
                <span><i class="el-icon-s-finance"></i> 支出统计</span>
              </template>
              <top-up-statistical/>
            </el-tab-pane>
            <el-tab-pane name="browsingHistory">
              <template #label>
                <span><i class="el-icon-s-claim"></i> 浏览历史</span>
              </template>
              <browsing-history/>
            </el-tab-pane>
            <el-tab-pane name="myCollection">
              <template #label>
                <span><i class="el-icon-star-on"></i> 我的收藏</span>
              </template>
              <my-collection/>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import orderApi from '../../api/order'
import { reactive, toRefs, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dictItemApi from '../../api/dictItem'
import BasicInfo from './profile/basicInfo.vue'
import SelfInfo from './profile/selfInfo.vue'
import ResetPwd from './profile/resetPwd.vue'
import PerfectInfo from './profile/perfectInfo.vue'
import OrderStatistical from './statistical/orderStatistical.vue'
import TopUpStatistical from './statistical/topUpStatistical.vue'
import BrowsingHistory from './history/browsingHistory.vue'
import MyCollection from './collection/myCollection.vue'

export default {
  name: 'Center',
  components: {
    BasicInfo,
    SelfInfo,
    ResetPwd,
    PerfectInfo,
    OrderStatistical,
    TopUpStatistical,
    BrowsingHistory,
    MyCollection
  },
  setup () {
    const route = useRoute()
    const store = useStore()
    const router = useRouter()
    const state = reactive({
      // 订单列表
      orderList: [],
      total: 0,
      // 状态
      statusOptions: [],
      queryParams: {
        current: 1,
        size: 10,
        id: undefined,
        status: undefined
      },
      tableHeight: window.innerHeight - 460,
      activeTopTab: route.query.tab1 !== undefined ? `${route.query.tab1}` : 'myOrder',
      activeSecondTab: route.query.tab2 !== undefined ? `${route.query.tab2}` : 'perfectInfo'
    })
    let userInfo = store.getters.userInfo
    //----------------------method start

    //--------------------我的订单操作 start
    // 获取客户订单列表
    const getMemberOrders = async () => {
      const { data: { records, total } } = await orderApi.getMemberOrders({ ...state.queryParams })
      state.orderList = records
      state.total = total
      // console.log(total)
    }
    // 触发当前页
    const currentChange = (currentPage) => {
      // console.log('触发了currentChange', currentPage)
      state.queryParams.current = currentPage
      getMemberOrders()
    }
    // 触发每页显示数量
    const sizeChange = (pageSize) => {
      // console.log('触发了sizeChange', sizeChange)
      state.queryParams.size = pageSize
      getMemberOrders()
    }
    // 取消订单
    const cancelOrder = (orderId) => {
      console.log(orderId)
      ElMessageBox.confirm('确定要取消订单吗~', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderApi.cancelMemberOrder(orderId).then(res => {
          ElMessage.success('取消订单成功')
          getMemberOrders()
        })
      }).catch(error => {
        ElMessage.warning('正在取消...')
        setTimeout(() => {
          ElMessage.success('取消成功')
        }, 2000)
      })
    }
    // 取我的订单项目
    const toMyOrderItems = (orderId) => {
      router.push({
        path: '/order/orderItems',
        query: {
          orderId: orderId
        }
      })
    }
    // 获取状态列表
    const getDictItems = () => {
      dictItemApi.getDictItems('beauty_member_order_status').then(response => {
        state.statusOptions = response.data
      })
    }
    // 查询按钮
    const handleQuery = () => {
      state.queryParams.current = 1
      getMemberOrders()
    }
    let queryForm = ref(null)
    // 重置表单
    const resetQuery = () => {
      queryForm.value.resetFields()
      handleQuery()
    }
    // 去付款
    const toPay = (order) => {
      ElMessageBox.confirm('确定要付款吗~', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先判断余额是否足够
        if (userInfo.amount < order.totalAmount) {
          ElMessageBox.confirm('您的余额不足, 是否去充值?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            router.push('/topUp')
          }).catch(() => {
            ElMessage.warning('正在取消...')
            setTimeout(() => {
              ElMessage.success('取消付款成功')
            }, 2000)
          })
        } else {
          // 付款
          orderApi.confirmMemberOrderPay(order.id).then(res => {
            ElMessage.success('付款成功')
            // 刷新页面
            getMemberOrders()
          }).catch(() => {
            ElMessage.error('付款失败')
          })
        }
      }).catch(error => {
        ElMessage.warning('正在取消...')
        setTimeout(() => {
          ElMessage.success('取消付款成功')
        }, 2000)
      })


    }
    // 去确认已服务
    const toConfirm = (orderId) => {
      ElMessageBox.confirm('确定要确认服务已完毕吗~', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderApi.confirmMemberOrder(orderId).then(res => {
          ElMessage.success('确认已服务完毕成功')
          // 刷新页面
          getMemberOrders()
          // 跳转评价页面
        })
      }).catch(error => {
        ElMessage.warning('正在取消...')
        setTimeout(() => {
          ElMessage.success('取消成功')
        }, 2000)
      })
    }
    // 去看服务进度
    const toProgress = (orderId) => {
      router.push({
        path: '/order/progress',
        query: {
          orderId: orderId
        }
      })
    }
    // 去评价
    const toEvaluation = (orderId) => {
      router.push({
        path: '/order/evaluation',
        query: {
          orderId: orderId
        }
      })
    }
    //--------------------我的订单操作 end

    //----------------------method end

    //=----------------钩子

    onMounted(() => {
      getMemberOrders()
      getDictItems()

    })
    //=----------------钩子

    return {
      queryForm,
      userInfo,
      ...toRefs(state),
      toConfirm,
      toProgress,
      toEvaluation,
      toPay,
      handleQuery,
      cancelOrder,
      resetQuery,
      getMemberOrders,
      toMyOrderItems,
      currentChange,
      sizeChange,
    }
  }
}
</script>


<style scoped lang="scss">

</style>
